#include <pthread.h>
#include "tcp_socket.hpp"
#include <unordered_map>

std::unordered_map<std::string, std::string> _dictionaries = {
  {"nihao", "你好"},
  {"637","刘三七"},
  {"zph","招聘会"}
};

std::string get_rsp(const std::string &key){
  auto it = _dictionaries.find(key); 
  if(it != _dictionaries.end()){
     return it->second;  //输入"nihao"输出 "你好"
  }
  return "不要乱说话";
}

void* entry(void* arg) //线程入口函数
{
  TcpSocket* conn_sock = (TcpSocket*)arg;
  while(1){
    std::string buf;
    bool ret = conn_sock -> Recv(&buf);
    if(ret == false){
      conn_sock->Close();
      break;
    }
    std::string data = get_rsp(buf);
    ret = conn_sock->Send(data);
    if(ret == false){
      conn_sock->Close();
      break;
    }
  }
  conn_sock->Close();
  delete conn_sock;
  return NULL;
}
bool new_worker(TcpSocket* conn_sock)
{
  pthread_t tid;
  int ret = pthread_create(&tid,NULL,entry,(void*)conn_sock);
  if(ret != 0){
    std::cout<<"thread create error\n";
    return false;
  }
  pthread_detach(tid);//线程退出直接释放资源
  return true;
}

int main()
{
    TcpSocket lst_sock;
    //1. 创建套接字
    CHECK_RET(lst_sock.Socket());
    //2. 绑定地址信息
    CHECK_RET(lst_sock.Bind("192.168.197.128",3090));
    //3. 开始监听
    CHECK_RET(lst_sock.Listen());
    while(1){
        //4. 获取新建连接
        TcpSocket* conn_sock = new TcpSocket(); //在堆上申请一个空间，给conn_sock分配一块空间。
        // 避免每次循环上去之后，conn_sock的空间被释放，这样会导致运行的线程出错，导致非法寻址。
        std::string client_ip;
        uint16_t client_port;
        bool ret = lst_sock.Accept(conn_sock, &client_ip, &client_port);
        if (ret < 0) {
            continue;
        }
        std::cout << "new connect:" << client_ip << ":" << client_port << std::endl;
        //5. 通过新建连接与客户端通信
        new_worker(conn_sock);
        //conn_sock.Close(); 线程之间共享文件描述表。主线程会运行到这里，所以不能在此处关闭。
    }

    //6. 关闭套接字
    lst_sock.Close();
    return 0;
}
